package cn.gzsxt.filter;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.gzsxt.utils.CookieUtils;


public class CheckLoginFilter implements Filter {
	//放行uri的集合
	private List<String> allowsList;
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		
		String allowsUri = filterConfig.getInitParameter("allowsUri");
		System.out.println(allowsUri);
		//将需要放行的多个uri 切成成一个个数组
		String[] arr = allowsUri.split(",");
		
		allowsList = Arrays.asList(arr);
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse resp = (HttpServletResponse)response;
		//获取请求路径 = 上下文路径+ 资源名称  uri
		String uri = req.getRequestURI();
		
		//使用 斜杠 / 写个 请求的uri:目的是为了得到最后一部分页面名称如: home.jsp login.jsp
		String[] uriArr = uri.split("/");
		//获取 数组的最后一个元素就是页面  home.jsp login.jsp
		String pageName = uriArr[uriArr.length-1];
		
		
		//chain.doFilter(req, resp);
		//如果请求的uri包含放行的集合中就放行, 静态资源  样式css,图片img,js文件,字体 fonts 都需要放行
		if(allowsList.contains(pageName) 
				|| uri.contains("/css/") 
				|| uri.contains("/js/") 
				|| uri.contains("/img/")
				|| uri.contains("/fonts/")
				){
			chain.doFilter(req, resp);
		}else{
			//任务
			//自己判断是否登录,登录成功以后的信息保存Cookie中的
			//使用CookieUtils 获取本地Cookie信息,判断是否有Cookie信息,有登录了:放行,没有.跳转到登录页面
			String sysUserJsonStr = CookieUtils.getCookieValue(req, "sysUser", true);
			System.out.println("sysUserJsonStr :"+sysUserJsonStr);
			if(sysUserJsonStr != null){//登录过,还在登录的有效期内:放行
				chain.doFilter(req, resp);
			}else{//没有登录:打回登录页面
				resp.sendRedirect(req.getContextPath()+"/login/syslogin.jsp");
			}
		}
	}
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}
}
